package com.summer.framework.core.category;

import com.summer.framework.base.cache.CacheService;
import com.summer.framework.core.cache.LocalCacheService;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description:
 *
 * @auther Ice Yang
 * Date 2025/9/30 17:13
 */
@Component
public class CategoryCache {

    private static final Map<String,String> CACHE = new ConcurrentHashMap<>();

    private static CacheService service;

    public CategoryCache(CacheService service) {
        CategoryCache.service = service;
    }

    /**
     * 获取缓存
     * @param key
     * @return
     */
    public static void set(String key, String value){
        // 如果是本地缓存，则放入本地缓存中
        if(service instanceof LocalCacheService){
            service.setObject(key,value);
        } else {
            // 如果是redis缓存，则放入本地内存和redis中
            CACHE.put(key,value);
            //存放redis
            service.setObject(key,value);
        }
    }

    /**
     * 获取缓存
     * @param key
     * @return
     */
    public static String get(String key){
        // 如果是本地缓存，则从本地缓存中获取
        if(service instanceof LocalCacheService){
            return service.getObject(key,String.class);
        }
        String value = CACHE.get(key);
        // 如果缓存不为空，则返回结果
        if(value != null && !value.isBlank()){
            return value;
        }
        // 日过缓存为空，则从redis中获取
        value = service.getObject(key,String.class);
        // 如果redis中不为空，则放入缓存中
        if(value != null && !value.isBlank()){
            CACHE.put(key,value);
        }
        return value;
    }

    /**
     * 删除缓存
     * @param key
     */
    public static void delete(String key){
        if(service instanceof LocalCacheService){
            service.delete(key);
            return;
        }
        service.delete(key);
        CACHE.remove(key);
    }

    /**
     * 删除缓存
     * @param key
     */
    public static void delete(List<String> key){
        if(service instanceof LocalCacheService){
            service.delete(key);
            return;
        }
        service.delete(key);
        key.forEach(CACHE::remove);
    }

}
